//
//  WXStatusViewModel.swift
//  weibo
//
//  Created by 王旭 on 16/4/20.
//  Copyright © 2016年 王旭. All rights reserved.
//

//对应WXHomeCell

import UIKit
import SDWebImage
import YYText
import SVProgressHUD

class WXStatusViewModel: NSObject {

    //管理cell的数据
    var status: WXStatusModel?{
        didSet{
            //调用判断会员等级图片
            chooseMemberImage()
            
            //添加转发微博内容
            addRetweetedContent()
            
            //格式化来源
            formatSource()
            
            //转发微博配图的大小
            retweetedPhotoSize = CalcRetweetedPhotoSize(status?.retweeted_status?.pic_urls)
            //原创微博配图大小
            orginPhotoSize = CalcRetweetedPhotoSize(status?.pic_urls)
            
            //处理时间
            createDate = self.sinaDate(status?.created_at)
            
            //self.attributedText(status?.text ?? "")
            originalAttributedString = self.attributedText(status?.text ?? "")
        }
    }
    
    //会员图标
    var memberImage: UIImage?
    // 转发微博的内容
    var retweetText: String?
    //来源
    var source :String?
    //转发微博配图的大小
    var retweetedPhotoSize : CGSize = CGSizeZero
    //原创微博配图大小
    var orginPhotoSize : CGSize = CGSizeZero
    
    // 距离当前时间的微博创建时间（xx分钟前 ）
    var createAtText: String? {
        return dealCreateAtText(createDate ?? NSDate())
    }
    
    // 原创微博的富文本内容
    var originalAttributedString: NSAttributedString?
    //转发微博富文本
    var retweetAttributedString: NSAttributedString?
    
    
    //处理首页微博图片表情&特殊字符高亮
    func attributedText(text: String) -> NSAttributedString {
        
        // 原生的富文本
        let attributeString = NSMutableAttributedString(string: text)
        
        var results = [WXMatchResult]()
        // 1. 匹配出表情字符串
        // \\[[a-zA-Z0-9\\u2E80-\\u9FFF]+\\]
        (text as NSString).enumerateStringsMatchedByRegex("\\[[a-zA-Z0-9\\u2E80-\\u9FFF]+\\]") { (count, captureString, captureRange, _) -> Void in
            //--------------------以下为测试代码-----------------
            //            print("\(captureString.memory)---\(captureRange.memory)")
            //--------------------以上为测试代码-----------------
            
            let result = WXMatchResult(captureString: captureString.memory!, range: captureRange.memory)
            results.append(result)
            
            //            // 2. 通过表情字符串找到对应的表情模型
            //            if let emoticon = HMEmoticonKeyBoardViewModel.sharedViewModel.emoticonWithChs(captureString.memory! as String) {
            //                print(emoticon)
            //
            //                // 3. 再通过表情模型生成表情图片的富文本
            //                let image =  UIImage(named: "\(emoticon.folderName ?? "")/\(emoticon.png ?? "")", inBundle: HMEmoticonKeyBoardViewModel.sharedViewModel.emoticonBundle, compatibleWithTraitCollection:  nil)
            //                // 初始化文字附件
            //                let attachment = HMTextAttachment()
            //                attachment.image = image
            //                let font = UIFont.systemFontOfSize(HMStatusCellContentFontSize)
            //                // 设置文字附件的大小
            //                attachment.bounds = CGRect(x: 0, y: -4, width: font.lineHeight, height: font.lineHeight)
            //
            //                // 初始化一个富文本
            //                let attr = NSAttributedString(attachment: attachment)
            //                //    并且把对应位置的表情文字给替换掉
            //                
            //                attributeString.replaceCharactersInRange(captureRange.memory, withAttributedString: attr)
            //                
            //            }
        }
        // 为了防止越界异常，所以我们倒着遍历
        for value in results.reverse() {
            // 2. 通过表情字符串找到对应的表情模型
            if let emoticon = WXEmotionViewModel.sharedEmotionViewModel.emoticonWithChs(value.captureString as String) {
                print(emoticon)
                
                // 3. 再通过表情模型生成表情图片的富文本
                let image =  UIImage(named: "\(emoticon.folderName ?? "")/\(emoticon.png ?? "")", inBundle: WXEmotionViewModel.sharedEmotionViewModel.emotionBundel, compatibleWithTraitCollection:  nil)
                //                attachment = [NSMutableAttributedString yy_attachmentStringWithContent:image contentMode:UIViewContentModeCenter attachmentSize:image.size alignToFont:font alignment:YYTextVerticalAlignmentCenter];
                
                let font = UIFont.systemFontOfSize(ContentFontSize)
                
                let attr = NSMutableAttributedString.yy_attachmentStringWithContent(image, contentMode: UIViewContentMode.ScaleAspectFill, attachmentSize: CGSize(width: font.lineHeight, height: font.lineHeight), alignToFont: font, alignment: YYTextVerticalAlignment.Center)
                
//                // 初始化文字附件
//                let attachment = WXTextAttachment()
//                attachment.image = image
//                let font = UIFont.systemFontOfSize(ContentFontSize)
//                // 设置文字附件的大小
//                attachment.bounds = CGRect(x: 0, y: -4, width: font.lineHeight, height: font.lineHeight)
//                
//                // 初始化一个富文本
//                let attr = NSAttributedString(attachment: attachment)
                
                //并且把对应位置的表情文字给替换掉
                attributeString.replaceCharactersInRange(value.range, withAttributedString: attr)
            }
        }
        //设置字体颜色
        attributeString.addAttribute(NSForegroundColorAttributeName, value: UIColor.darkGrayColor(), range: NSMakeRange(0, attributeString.length))
        
        // 添加特殊字符文字颜色
        // 话题
        addLinkColor("#[^#]+#", attributeString: attributeString)
        // @
        addLinkColor("@[\\u4e00-\\u9fa5A-Za-z0-9_\\-]+", attributeString: attributeString)
        // url
        addLinkColor("([hH]ttp[s]{0,1})://[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\-~!@#$%^&*+?:_/=<>.',;]*)?", attributeString: attributeString)
        
        //设置字体大小
        attributeString.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(ContentFontSize), range: NSMakeRange(0, attributeString.length))
        
        return attributeString

    }

    
    private var createDate: NSDate?
    
    /// 通过一个创建时间的字符串格式化成 NSDate
    private func sinaDate(createAt: String?) -> NSDate? {
        
        // 时间字符串
        guard let create_at = createAt else {
            return nil
        }
        
        // 转成 NSDate
        // 初始化时间格式化器
        let fm = NSDateFormatter()
        // 指定格式字符串   Sun Nov 22 11:25:56 +0800 2015
        fm.locale = NSLocale(localeIdentifier: "en")
        // 2015-08-10 10:10:10 yyyy-MM-dd HH:mm:ss
        fm.dateFormat = "EEE MMM dd HH:mm:ss z yyyy"
        let createDate = fm.dateFromString(create_at)!
        return createDate
    }
    
    //添加特殊字符的颜色
    func addLinkColor(regex: String, attributeString: NSMutableAttributedString){
        
        (attributeString.string as NSString).enumerateStringsMatchedByRegex(regex) { (_, captureString, captureRange, _) -> Void in
            //--------------------以下为测试代码-----------------
            //            print(captureString.memory)
            //--------------------以上为测试代码-----------------
            attributeString.addAttribute(NSForegroundColorAttributeName, value: UIColor(red: 80/255, green: 125/255, blue: 175/255, alpha: 1), range: captureRange.memory)
            
            //            YYTextBorder *border = [YYTextBorder borderWithFillColor:[UIColor grayColor] cornerRadius:3];
            //
            //            YYTextHighlight *highlight = [YYTextHighlight new];
            //            [highlight setColor:[UIColor whiteColor]];
            //            [highlight setBackgroundBorder:highlightBorder];
            //            highlight.tapAction = ^(UIView *containerView, NSAttributedString *text, NSRange range, CGRect rect) {
            //                NSLog(@"tap text range:...");
            //                // 你也可以把事件回调放到 YYLabel 和 YYTextView 来处理。
            //            };
            //
            //            // 2. 把"高亮"属性设置到某个文本范围
            //            [attributedText yy_setTextHighlight:highlight range:highlightRange];
            
            // 1. 初始化一个背景对象
            let border = YYTextBorder(fillColor: UIColor(red: 177/255, green: 215/255, blue: 255/255, alpha: 1), cornerRadius: 3)
            // 边框的边距
            border.insets = UIEdgeInsetsZero
            
            
            // 2. 初始化高亮对象
            let highlight = YYTextHighlight()
            // 设置高亮的时候的文字颜色
            highlight.setColor(UIColor(red: 80/255, green: 125/255, blue: 175/255, alpha: 1))
            // 设置高亮时的背景
            highlight.setBackgroundBorder(border)
            let s = (captureString.memory)! as String
            // void(^YYTextAction)(UIView *containerView, NSAttributedString *text, NSRange range, CGRect rect);
            highlight.tapAction = { (containerView: UIView, text: NSAttributedString, range: NSRange, rect: CGRect)->() in
                print("特殊字符点击了")
                SVProgressHUD.showInfoWithStatus(s)
            }
            // 3. 将高亮对象添加到attributedString里面
            attributeString.yy_setTextHighlight(highlight, range: captureRange.memory)
        }
    }
    
    // 处理时间的方法
    private func dealCreateAtText(createDate: NSDate) -> String {
        //        // 时间字符串
        //        guard let create_at = status?.created_at else {
        //            return ""
        //        }
        //
        //        // 转成 NSDate
        //        // 初始化时间格式化器
        let fm = NSDateFormatter()
        //        // 指定格式字符串   Sun Nov 22 11:25:56 +0800 2015
        fm.locale = NSLocale(localeIdentifier: "en")
        //        // 2015-08-10 10:10:10 yyyy-MM-dd HH:mm:ss
        //        fm.dateFormat = "EEE MMM dd HH:mm:ss z yyyy"
        //        let createDate = fm.dateFromString(create_at)!
        //        print(createDate)
        
        let calendar = NSCalendar.currentCalendar()
        
        
        
//以下代码供测试使用＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝
        // createDate = NSDate().dateByAddingTimeInterval(-61 * 60 * 24 * 365)
//以上代码供测试使用＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝
        
        
        // 与当前时间进行对比
        if isDateInThisYear(createDate) { // createDate是否是今年
            if calendar.isDateInToday(createDate) {// 是今天
                let currentDate = NSDate()
                // 求出当前时间与创建时间的差值（秒）
                let timeInterval = currentDate.timeIntervalSinceDate(createDate)
                
                if timeInterval < 60 {// 是否是1分钟之内
                    return "刚刚"
                }else if timeInterval < 3600 { // 是否是1小时之内
                    // xx 分钟前
                    return "\(Int(timeInterval) / 60)分钟前"
                }else{
                    // xx 小时前
                    return "\(Int(timeInterval) / 3600)小时前"
                }
            }else if calendar.isDateInYesterday(createDate) {//是昨天
                // 昨天 10:10
                fm.dateFormat = "昨天 HH:mm"
                return fm.stringFromDate(createDate)
            }else{
                // 其他 08-10 10:10
                fm.dateFormat = "MM-dd HH:mm"
                return fm.stringFromDate(createDate)
            }
        }else{
            //            createAtText = "不是今年"
            fm.dateFormat = "yyyy-MM-dd HH:mm"
            return fm.stringFromDate(createDate)
        }
    }
    /// 传入一个时间，与当前时间进行对比 ，返回是否是当前时间的年分
    private func isDateInThisYear(targetDate: NSDate) -> Bool {
        // 当前时间
        let currentDate = NSDate()
        
        let fm = NSDateFormatter()
        fm.dateFormat = "yyyy"
        // 取出两个时间的年份
        let targetYear = fm.stringFromDate(targetDate)
        let currentYear = fm.stringFromDate(currentDate)
        
        return targetYear == currentYear
    }
    
    //更新图片大小
    func updatePhotoSingleSize() {
        retweetedPhotoSize = calcPhotoSingleSize(status?.retweeted_status?.pic_urls)
        orginPhotoSize = calcPhotoSingleSize(status?.pic_urls)
    }
    
    //计算图片大小
    func calcPhotoSingleSize(pic_urls:[WXHomePhotoModel]?)->CGSize {
        
        guard let urlStr = pic_urls?.first?.thumbnail_pic else{
            return CGSizeZero
        }
        
        //获取下载好的图片
        if let photo = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(urlStr) {
            //获取缩放比
            let scale = UIScreen.mainScreen().scale
            //获得图片大小
            var cachePhotoSize = CGSize(width: photo.size.width * scale, height: photo.size.height * scale)
            
            //设置一个最小的宽度,不足就拉伸
            if cachePhotoSize.width < 50 {
                cachePhotoSize.height = (120 / cachePhotoSize.width) * cachePhotoSize.height
                cachePhotoSize.height = (cachePhotoSize.height > 100) ? 100 : cachePhotoSize.height
                cachePhotoSize.width = 120
                
            }
            return cachePhotoSize
            
        }
        return CGSizeZero
    }
    
    //判断会员等级图片
   private func chooseMemberImage() {
//        if let m = status?.user?.mbRank where (m<7 && m>0) {
//            memberImage = UIImage(named: "common_icon_membership_level\(m)")
//        }
        guard let m = status?.user?.mbrank else {
            print("为空")
            return
        }
        
//        print(m)
        
        if m>0 && m<7 {
            memberImage = UIImage(named: "common_icon_membership_level\(m)")
        }
    }
    
    private func addRetweetedContent() {
        if let r = status?.retweeted_status {
            if let name = r.user?.screen_name, content = r.text {
                retweetText = "@\(name):\(content)"
                retweetAttributedString = self.attributedText(retweetText!)
//                print(retweetText)//数据存在
            }
        }
    }
    
    //格式化来源
   private func formatSource() {
        //"<a href=\"http://app.weibo.com/t/feed/3auC5p\" rel=\"nofollow\">皮皮时光机</a>"
//        print(status?.source)
        //判断是否为空
        guard let s = status?.source else{
            return
        }
        //截取字符串
        if let start = s.rangeOfString("\">")?.endIndex,end = s.rangeOfString("</")?.startIndex {
            let result = s.substringWithRange(start..<end)
            source = "来自 \(result)"
        }
    }
    
    //转发微博配图的大小
   private func CalcRetweetedPhotoSize(pic_urls:[WXHomePhotoModel]?)->CGSize {
        //获得图片张数
    let count = pic_urls?.count ?? 0
    //是否为0
    if count == 0 {
        return CGSizeZero
    }
    //计算行数和列数
    let row = ((count - 1) / 3) + 1
    let col = count == 4 ? 2 : (count > 3 ? 3 : count)
    //计算行列间间距和图片宽高
    let margin : CGFloat = 5
    let retweetedPhotoWH : CGFloat = (SCREEN_W - 2 * HomeCellMargin - 2 * margin) / 3
    //计算
    let width = retweetedPhotoWH * CGFloat(col) + margin * CGFloat(col - 1)
    let height = retweetedPhotoWH * CGFloat(row) + margin * CGFloat(row - 1)
    
    
    return CGSize(width: width, height: height)

    }
    
}
